/**
 * Created by Dalyn on 2017/5/8.
 */
import React from "react";
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import {_Input,_Button,_Icon,_Modal} from 'ANT_DE';
const Input = _Input,
      Button = _Button,
      Icon = _Icon, Modal = _Modal;
import {Upload,message} from 'antd';


import SavePackStepMutation from './mutation/SavePackStep';  //保存

import DelQiniuFileMutation from "./mutation/DelQiniuFileMutation" // 删除图片

import GetQiNiuToken from "./mutation/GetQiNiuToken"  //上传图片

import './css/packStep.css';

/*
* 包装步骤  展示层
*asdasdasdsad
* */

function PackStepView (props){
    const data = props.data;
    return (<div>
            包装步骤展示层
        </div>
    )
}

/*导出组件*/
export default class PackStep extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
            stepArr:[{value:""},{value:""},{value:""}],  //步骤列表
            fileList:[[],[],[]],   //上傳文件列表
            previewImage: '',
            previewVisible:false  //图片预览
        };
        this.accept = ".jpg,.png,.git,.jpeg";
        this.handleChange = this.handleChange.bind(this);
        this.handlePreview = this.handlePreview.bind(this);
        this.handleCancel = this.handleCancel.bind(this);
        this.save = this.save.bind(this);

        this.removeItem = this.removeItem.bind(this);
        this.plus = this.plus.bind(this);
        this.handleChangeText = this.handleChangeText.bind(this);
        this.updataFile = this.updataFile.bind(this);
        this.picRemove = this.picRemove.bind(this);
        this.beforeUpload = this.beforeUpload.bind(this);
    }

    componentWillMount(){
        this.token = "";
        Relay.Store.commitUpdate(
            new GetQiNiuToken({}), {
                onSuccess: (res) => {
                    let errorCode = res.getQiNiuToken.getQiNiuToken.errorCode;
                    if(errorCode==0){
                        let qiniutoken = res.getQiNiuToken.getQiNiuToken.qiniutoken;
                        this.token = qiniutoken;
                    }
                }
            }
        );
    }

    componentDidMount(){}

    /*文本输入change*/
    handleChangeText = (e,index)=>{
        this.state.stepArr[index].value = e.target.value;
        this.setState({
            stepArr:this.state.stepArr
        });
    };



    // 删除图片
    picRemove(index){
        //下列固定为0，因为list最多只能上传一个，固0
        const name = this.state.fileList[index][0].response.key;
        const loading = message.loading("正在删除");
        Relay.Store.commitUpdate(
            new DelQiniuFileMutation({
                fileKey: name
            }),
            {
                onFailure: () => {
                },
                onSuccess: (response) => {
                    let errorCode = response.delQiniuFile.delQiniuFile.errorCode;
                    if (errorCode == 0) {
                        loading();
                    }
                }
            }
        )
    }

    plus(index){
        if(this.state.stepArr.length < 20){
            this.state.stepArr.splice(index+1,0,{value:""});
            this.state.fileList.splice(index+1,0,[]);
            this.setState({
                stepArr:this.state.stepArr,
                fileList:this.state.fileList
            })
        }else{
            message.error("最多不可超过20个")
        }
    }
    removeItem(index){
        this.state.stepArr.splice(index,1);
        this.state.fileList.splice(index,1);

        this.setState({
            stepArr:this.state.stepArr,
            fileList:this.state.fileList
        });
    }
    save(){
        console.log(this.state.fileList);

        Relay.Store.commitUpdate(
            new SavePackStepMutation({
                pdId:"TD20170503180000012309"
            }), {
                onFailure: () => {
                    console.log("请求失败")
                },
                onSuccess: (res)=> {
                    console.log(res);
                }
            }
        )
    }

     // 预览图片关闭
    handleCancel = ()=>{
        this.setState({previewVisible:false})
    }

    // change图片
    handleChange(index,{file,fileList},fileLi,event){

        console.log(file.status);

        this.state.fileList[index] = fileList;
        this.setState({
            fileList:this.state.fileList
        },()=>{
            console.log(this.state.fileList);
        });


        // 上传成功
        if(file.status === "done" ){
            message.success("上传成功");

        }
        //上传失败
        if(file.status === "error"){
            message.error("上传图片失败，请重试");
        }
        // 删除图片
        if(file.status === "removed"){
            console.log("删除图片");
        }
    }


    // 上传之前进行验证
    beforeUpload(file){
        const MaxSize = 20;  //最大限度 20M;
        // 图片格式
        if(file.type !== "image/jpeg" && file.type !== "image/jpg" && file.type !== "image/png" && file.type !== "image/gif"){
            message.error("图片格式错误");
            return false;
        }

        // 图片大小
        if( file.size / 1024 / 1024 > MaxSize ){
            message.error("图片大小超过限制");
            return false;
        }
    }
    // 预览图片
    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }
    updataFile(file,index,id){
        return {file:file,token:this.token}
    }

    render(){
        const {stepArr,previewVisible, previewImage, fileList} = this.state,
            {} = this.props;

        const uploadButton = (
            <Button>
                <Icon type="upload" /> 上传图片
            </Button>
        );

        return (
            <div className="poduction_manage_tab_box" >
                <div className="product_packagSteps">

                    {
                        stepArr.map((item,index)=>
                            <div className="packagSteps-item" key={index}>
                                <div className="packagSteps-item_content">
                                    <div className="packagSteps-icon-stepKey">
                                <span>
                                    {index+1}
                                </span>
                                    </div>
                                    <div className="packagSteps-textInput">
                                        <Input type="textarea" rows={4} maxLength="300" value={item.value}
                                               onChange={(e)=>this.handleChangeText(e,index)}
                                               placeholder="点击这里输入步骤"/>
                                    </div>
                                    <aside className="_left packagSteps_asideRight">
                                        {
                                            index !== 0 && <Icon data-type="close" type="close-circle" onClick={()=>this.removeItem(index)} />
                                        }
                                        <Icon data-type="plus" type="plus" onClick={()=>this.plus(index)} />
                                    </aside>
                                </div>

                                <div className="packagSteps_updata-info-pic">
                                    <ul className="packagSteps_updata-info-picList">
                                        <li></li>
                                        <Upload
                                            className="packagSteps_updata"
                                            action="http://up-z2.qiniu.com"
                                            data={this.updataFile}
                                            beforeUpload={this.beforeUpload}
                                            onRemove={()=>this.picRemove(index)}
                                            listType="picture-card"
                                            fileList={fileList[index]}
                                            onPreview={this.handlePreview}
                                            onChange={(file,fileList,event)=>{this.handleChange(index,file,fileList,event)}}
                                            accept={this.accept}
                                        >
                                            {fileList[index].length >= 1 ? null : uploadButton}
                                        </Upload>

                                        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                                        </Modal>
                                    </ul>
                                </div>
                            </div>
                        )
                    }


                    <div className="packagSteps_footer">
                        <Button type="primary" onClick={this.save}> 保存 </Button>
                    </div>
                </div>
            </div>
        )
    }
}